<?php

namespace app\api\controller\activity;

use app\admin\model\member\ActivityCollect;
use app\admin\model\vactivities\Ticket;
use app\common\controller\Api;
use app\common\library\Iden;
use app\admin\model\vactivities\Activity as act;
use app\admin\model\member\Account;
use think\Db;

// 允许跨域
header('Access-Control-Allow-Origin:*');//允许跨域

/**
 * 会员课程新高考专区
 */
class Activity extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $tag_model;
    private $cat_model;
    private $ticket_model;
    protected $aact;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vactivities\Activity;
        $this->tag_model = new  \app\admin\model\superdata\Activitytags;
        $this->cat_model = new  \app\admin\model\superdata\Activitycategory;
        $this->ticket_model = new \app\admin\model\vactivities\Ticket;
       // $this->aact = new \app\api\controller\activity\activity;
    }


    /**
     * @desc 活动详情页
     * @param $ids 活动ids
     * */
    public function detail(){

        $ids = $this->request->param("ids");
        if (!$ids) {
            $this->error(__('获取参数错误'),'',0);
        }
        $ids =  Iden::decrypt($ids);
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
       // print_r($row);die;
        $data = [];
        $data['name'] = $row['name'];
        $data['summary'] = $row['summary'];
        $data['detail'] = $row['detail'];
        $data['duration'] = s_to_hs($row['duration']);
        $data['startTime'] = date('Y-m-d H:i:s',$row['startTime']);
        $tlist = $this->ticket_model->getTicketList($row['id'],Ticket::TICKET_TYPE_2,$row['admin_id']);
        if($tlist){
            $price = self::max_min($tlist);
        }
        $data['price_min'] = isset($price) && !empty($price['min']) ? $price['min']:0;
        $data['price_max'] = isset($price) && !empty($price['max']) ? $price['max']:0;
        $data['id'] = Iden::encrypt($row['id']);
        $data['link_url'] = $row['link_url'];
        $data['isticket'] = $row['isticket'];
        $data['tags'] = $this->tag_model->getTagsArrNameById($row['tags']);
        $data['category']=$this->cat_model->getcateNameById($row['category']);

        $data['isseries'] = isset($row['series_id']) && $row['series_id'] > 0 ? 1:0;//1是系列活动 0 否
        if($this->auth->isLogin()){
            //判断是否登录
            $data['iscollect'] = $this->Iscollect($row['id']);//是否已收藏
        }else{
            $data['iscollect'] = 0;//是否已收藏
        }

        if($row['thumb']){
            $thumbArr = explode(',',$row['thumb']);
            $data['thumb'] = !empty($thumbArr) ? $thumbArr:'';
        }
        $uInfo = Account::getUsrInfoById($row['admin_id']);
        $data['uid'] = Iden::encrypt($row['admin_id']);
        if($uInfo){
            $data['nickname'] = !empty($uInfo['nickname']) ? $uInfo['nickname']:'';
            $data['avatar'] = !empty($uInfo['avatar']) ? $uInfo['avatar']:'';
            $data['introduction'] = !empty($uInfo['introduction']) ? $uInfo['introduction']:'';

        }else{
            $data['nickname'] ='';
            $data['avatar'] ='';
            $data['introduction'] ='';
        }
        Db::table('activity')->where('id', $ids)->setInc('clk_cnt');//每浏览一次增1
        $this->success(__('读取成功'), $data,200);
    }




    /*
     * $tlist 获取的价格数组
     * 最大值与最小值
     */
   static public function max_min($tlist){
        if(empty($tlist))
            return false;
        $m = [];
        foreach($tlist as $v){
            $m[] = $v['price'];
        }

        $max = max($m);
        $min = min($m);
        unset($m);
        $data['max'] = $max;
        $data['min'] = $min;
        //$price = $min.'--'.$max;
        return $data;
    }


    /*
     * 活动分类列表
     */
   public function category_list(){
       $cate = $this->request->param('cate_id',0);//分类id
       $map['status'] = 1;
       $res = Db::name('activity_category')->where($map)->field('*')->order('sort desc,createTime desc')->select();
       $list = [];
       if($res){
           foreach($res as $k=>$v){
               $list[$k]['id'] = $v['id'];
               $list[$k]['name'] = $v['name'];
           }
       }else{
           return '';
       }
       $this->success(__('读取成功'), $list,200);
   }


   /*
    * 首页即将开始活动接口
    */
   public function begin_activity(){
       $nowTime = time();
       $time = strtotime('-30 day');
      // $sql = 'select * from table where add_time >='.$time

       $map = " (startTime+duration) > $nowTime and status = 1";
       $per_page = $this->request->get('per_page', 1);
       $limit  = (int)$this->request->get('limit', 20);
       $offset = ($per_page - 1) * $limit;
       $list = $this->model
           ->where($map)
           ->order('startTime ASC')
           ->limit($offset, $limit);
       $r = $list->select();
       $count = count($r);
       $list = [];


       foreach($r as $k=>$row){
           $row->visible(['id','name','thumb','startTime','duration','summary','category','tags','detail',
               'price','admin_id','nickname','avatar','link_url','introduction','price_min','price_max',
               'isticket','series_id','isseries','iscollect']);#iscollect是否收藏
           $tlist = $this->ticket_model->getTicketList($row['id'],Ticket::TICKET_TYPE_2,$row['admin_id']);
           if($tlist){
               $price = self::max_min($tlist);
           }
           $list[$k]['id'] = Iden::encrypt($row['id']);
           $list[$k]['name'] = $row['name'];
           $list[$k]['price_min'] = isset($price) && !empty($price['min']) ? $price['min']:0;
           $list[$k]['price_max'] = isset($price) && !empty($price['max']) ? $price['max']:0;

           $list[$k]['summary'] = $row['summary'];
           $list[$k]['isticket'] = $row['isticket'];
           $list[$k]['duration'] = s_to_hs($row['duration']);
           $list[$k]['startTime'] = date('Y-m-d H:i:s',$row['startTime']);
           $list[$k]['isseries'] = isset($row['series_id']) && ($row['series_id'] > 0) ? 1:0;
           if($row['thumb']){
               $thumbArr = explode(',',$row['thumb']);
               $list[$k]['thumb'] = !empty($thumbArr) ? $thumbArr:'';
           }
           $list[$k]['uid'] = Iden::encrypt($row['admin_id']);
           $list[$k]['tags'] = $this->tag_model->getTagsNameById($row['tags']);
           $list[$k]['category'] = $this->cat_model->getcateNameById($row['category']);
           if($this->auth->isLogin()){
               //判断是否登录
               $list[$k]['iscollect'] = $this->Iscollect($row['id']);//是否已收藏
           }else{
                $list[$k]['iscollect'] = 0;//是否已收藏
           }

           $uInfo = Account::getUsrInfoById($row['admin_id']);
           if($uInfo){
               $list[$k]['nickname'] = !empty($uInfo['nickname']) ? $uInfo['nickname']:'';
               $list[$k]['avatar'] = !empty($uInfo['avatar']) ? $uInfo['avatar']:'';
               $list[$k]['introduction'] = !empty($uInfo['introduction']) ? $uInfo['introduction']:'';
           }else{
               $list[$k]['nickname'] ='';
               $list[$k]['avatar'] ='';
               $list[$k]['introduction'] ='';
           }

       }
       $result = array("total" =>$count, "rows" => $list);
       unset($list);
       $this->success(__('读取成功'), $result, 200);
   }


    /*
     * 首页最新活动接口
     */
    public function new_activity(){
        $nowTime = time();
        $map = " (startTime+duration) > $nowTime and status = 1";
        $per_page = $this->request->get('per_page', 1);
        $limit  = (int)$this->request->get('limit', 20);
        $offset = ($per_page - 1) * $limit;
        $list = $this->model
            ->where($map)
            ->order('createTime DESC')
            ->limit($offset, $limit);
        $r = $list->select();
        $count = count($r);
        $list = [];

        foreach($r as $k=>$row){
            $row->visible(['id','name','thumb','startTime','duration','summary','category','tags','detail','createTime','uid',
                'price','admin_id','nickname','avatar','link_url','introduction','price_min','price_max','isticket','series_id','isseries']);
            $tlist = $this->ticket_model->getTicketList($row['id'],Ticket::TICKET_TYPE_2,$row['admin_id']);
            if($tlist){
                $price = self::max_min($tlist);
            }
            $list[$k]['id'] = Iden::encrypt($row['id']);
            $list[$k]['name'] = $row['name'];
            $list[$k]['price_min'] = isset($price) && !empty($price['min']) ? $price['min']:0;
            $list[$k]['price_max'] = isset($price) && !empty($price['max']) ? $price['max']:0;

            $list[$k]['summary'] = $row['summary'];
            $list[$k]['isticket'] = $row['isticket'];
            $list[$k]['duration'] = s_to_hs($row['duration']);
            $list[$k]['startTime'] = date('Y-m-d H:i:s',$row['startTime']);
            $list[$k]['createTime'] = $row['createTime'];
            $list[$k]['isseries'] = isset($row['series_id']) && ($row['series_id'] > 0) ? 1:0;
            if($row['thumb']){
                $thumbArr = explode(',',$row['thumb']);
                $list[$k]['thumb'] = !empty($thumbArr) ? $thumbArr:'';
            }
            $list[$k]['uid'] = Iden::encrypt($row['admin_id']);
            $list[$k]['tags'] = $this->tag_model->getTagsNameById($row['tags']);
            $list[$k]['category'] = $this->cat_model->getcateNameById($row['category']);

            if($this->auth->isLogin()){
                //判断是否登录
                $list[$k]['iscollect'] = $this->Iscollect($row['id']);//是否已收藏
            }else{
                $list[$k]['iscollect'] = 0;//是否已收藏
            }


            $uInfo = Account::getUsrInfoById($row['admin_id']);
            if($uInfo){
                $list[$k]['nickname'] = !empty($uInfo['nickname']) ? $uInfo['nickname']:'';
                $list[$k]['avatar'] = !empty($uInfo['avatar']) ? $uInfo['avatar']:'';
                $list[$k]['introduction'] = !empty($uInfo['introduction']) ? $uInfo['introduction']:'';
            }else{
                $list[$k]['nickname'] ='';
                $list[$k]['avatar'] ='';
                $list[$k]['introduction'] ='';
            }

        }
        $result = array("total" =>$count, "rows" => $list);
        unset($list);
        $this->success(__('读取成功'), $result, 200);
    }
     /*
     * 首页推荐接口
     */
    public function recommand_activity(){

        $map['status'] = 1;
        $per_page = $this->request->get('per_page', 1);
        $limit  = (int)$this->request->get('limit', 20);
        $offset = ($per_page - 1) * $limit;
        $list = $this->model
            ->where($map)
            ->order(['isrecommend DESC','createTime DESC'])
            ->limit($offset, $limit);
        $r = $list->select();
       // echo $this->model->getLastSql();;die;
        $count = count($r);
        $list = [];

        foreach($r as $k=>$row){
            $row->visible(['id','name','thumb','startTime','duration','summary','category','tags','detail','createTime',
                'price','admin_id','nickname','avatar','link_url','introduction','price_min','price_max','isticket','series_id','isseries']);
            $tlist = $this->ticket_model->getTicketList($row['id'],Ticket::TICKET_TYPE_2,$row['admin_id']);
            if($tlist){
                $price = self::max_min($tlist);
            }
            $list[$k]['id'] = Iden::encrypt($row['id']);
            $list[$k]['name'] = $row['name'];
            $list[$k]['price_min'] = isset($price) && !empty($price['min']) ? $price['min']:0;
            $list[$k]['price_max'] = isset($price) && !empty($price['max']) ? $price['max']:0;

            $list[$k]['summary'] = $row['summary'];
            $list[$k]['isticket'] = $row['isticket'];
            $list[$k]['duration'] = s_to_hs($row['duration']);
            $list[$k]['startTime'] = date('Y-m-d H:i:s',$row['startTime']);
            $list[$k]['createTime'] = $row['createTime'];
            $list[$k]['isseries'] = isset($row['series_id']) && ($row['series_id'] > 0) ? 1:0;
            if($row['thumb']){
                $thumbArr = explode(',',$row['thumb']);
                $list[$k]['thumb'] = !empty($thumbArr) ? $thumbArr:'';
            }
            $list[$k]['uid'] = Iden::encrypt($row['admin_id']);
            $list[$k]['tags'] = $this->tag_model->getTagsNameById($row['tags']);
            $list[$k]['category'] = $this->cat_model->getcateNameById($row['category']);
            if($this->auth->isLogin()){
                //判断是否登录
                $list[$k]['iscollect'] = $this->Iscollect($row['id']);//是否已收藏
            }else{
                $list[$k]['iscollect'] = 0;//是否已收藏
            }
           // $list[$k]['iscollect'] = $this->Iscollect($row['id']);//是否已收藏
            $uInfo = Account::getUsrInfoById($row['admin_id']);
            if($uInfo){
                $list[$k]['nickname'] = !empty($uInfo['nickname']) ? $uInfo['nickname']:'';
                $list[$k]['avatar'] = !empty($uInfo['avatar']) ? $uInfo['avatar']:'';
                $list[$k]['introduction'] = !empty($uInfo['introduction']) ? $uInfo['introduction']:'';
            }else{
                $list[$k]['nickname'] ='';
                $list[$k]['avatar'] ='';
                $list[$k]['introduction'] ='';
            }
        }
        $result = array("total" =>$count, "rows" => $list);
        unset($list);
        $this->success(__('读取成功'), $result, 200);
    }
    /*
     * 判断是否能被收藏
     */
    public function Iscollect($aid){
        $uInfo = $this->auth->getUserInfo();//
       // $uInfo['id'] = Iden::encrypt($uInfo['id']);

        if(isset($uInfo) && !empty($uInfo['id'])){
            $rs = ActivityCollect::IsCollectById($aid,Iden::decrypt($uInfo['id']));
            if($rs)
                $iscollect = 1;
            else
                $iscollect = 0;
        }else{
            $iscollect = 0;
        }

        return $iscollect;
    }

}
